package com.yzg.simple.ip;
import org.lionsoul.ip2region.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @ClassName IpAddr
 * @Description TODO
 * @Authoe weiyan
 * @Date 2019/12/20 16:41
 * @Version 1.0
 **/

public class IpAddr {
    public static String findIpAddr(String argv,String type) {

        if (!Objects.nonNull(argv)) {
            throw new RuntimeException("IP不可为空");
        }
        int algorithm = DbSearcher.BTREE_ALGORITHM;
        String algoName = "B-tree";
        if ( Objects.nonNull(type) ) {
            if ( type.equalsIgnoreCase("binary")) {
                algoName  = "Binary";
                algorithm = DbSearcher.BINARY_ALGORITHM;
            } else if (type.equalsIgnoreCase("memory") ) {
                algoName  = "Memory";
                algorithm = DbSearcher.MEMORY_ALGORITYM;
            }
        }

        try {
            File filePath = new File("");
            String path =  filePath.getAbsolutePath()+"\\src\\main\\java\\com\\yzg\\simple\\ip\\data\\ip2region.db";
           /* RandomAccessFile randomAccessFile = new RandomAccessFile(path,"wr");
            FileChannel inputChannel = randomAccessFile.getChannel();*/
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config,path);
/*
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
*/

            //define the method
            Method method = null;
            switch ( algorithm )
            {
                case DbSearcher.BTREE_ALGORITHM:
                    method = searcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = searcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = searcher.getClass().getMethod("memorySearch", String.class);
                    break;
            }
               if (!Util.isIpAddress(argv)) throw new RuntimeException("该参数不是不是IP");
                DataBlock dataBlock = null;
                dataBlock = (DataBlock) method.invoke(searcher, argv);
                searcher.close();
/*               对数据进行重新定义
               Arrays.asList(dataBlock.getRegion().split("\\|")).stream().filter(newData -> newData.trim().getBytes().length >=3).collect(Collectors.toCollection(ArrayList::new)).forEach(System.err::println);
*/
            return dataBlock.toString();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DbMakerConfigException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        throw new RuntimeException("暂无返回值");
    }



/*    public static void main(String[] args) {
        try {
            File filePath = new File("");
            String path =  filePath.getAbsolutePath()+"\\src\\main\\java\\com\\yzg\\tcp\\ip\\data";
            DbSearcher _searcher = new DbSearcher(new DbConfig(), path+"\\ip2region.db");
            BufferedReader bfr   = new BufferedReader(new FileReader(path+"\\/ip.merge.txt"));
            BufferedWriter bwr   = new BufferedWriter(new FileWriter(path+"\\/error_log.txt", true));
            int errCount  = 0;
            int lineCount = 0;
            String str = null;

            while ( (str = bfr.readLine()) != null ) {
                StringBuffer line = new StringBuffer(str);
                //get first ip
                int first_idx   = line.indexOf("|");
                String first_ip = line.substring(0, first_idx);

                line = new StringBuffer( line.substring(first_idx + 1) );

                //get second ip
                int second_idx   = line.indexOf("|");
                String second_ip = line.substring(0, second_idx);

                //get addr
                String source_region = line.substring(second_idx + 1);

                //search from DbSearcher
                System.out.println("+---Start, start to search");
                System.out.println("+---[Info]: Source region = "+source_region);

                System.out.println("+---[Info]: Step1, search for first IP: "+first_ip);
                DataBlock fdata = _searcher.binarySearch(first_ip);
                if ( ! fdata.getRegion().equalsIgnoreCase( source_region ) ) {
                    System.out.println("[Error]: Search first IP failed, DB region = "+fdata.getRegion());
                    bwr.write("[Source]: Region: "+fdata.getRegion());
                    bwr.newLine();
                    bwr.write("[Source]: First Ip: "+first_ip);
                    bwr.newLine();
                    bwr.write("[DB]: Region: "+fdata.getRegion());
                    bwr.newLine();
                    bwr.flush();
                    errCount++;
                }

                System.out.println("+---[Info]: Step2, search for second IP: "+second_ip);
                DataBlock sdata = _searcher.btreeSearch(second_ip);
                if ( ! sdata.getRegion().equalsIgnoreCase( source_region ) ) {
                    System.out.println("[Error]: Search second IP failed, DB region = "+sdata.getRegion());
                    bwr.write("[Source]: Region: "+sdata.getRegion());
                    bwr.newLine();
                    bwr.write("[Source]: First Ip: "+second_ip);
                    bwr.newLine();
                    bwr.write("[DB]: Region: "+sdata.getRegion());
                    bwr.newLine();
                    bwr.flush();
                    errCount++;
                }

                lineCount++;
            }

            bwr.close();
            bfr.close();
            System.out.println("+---Done, search complished");
            System.out.println("+---Statistics, Error count = "+errCount
                    +", Total line = "+lineCount
                    +", Fail ratio = "+((float)(errCount/lineCount))*100+"%");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DbMakerConfigException e) {
            e.printStackTrace();
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }*/



}
